<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class vProduct extends Controller {

    /**
     * 商品列表显示数量
     */
    const LIST_LIMIT = 10;

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    /**
     * Product Detail
     * @param type $Query
     */
    public function view($Query) {
        // 推荐com，90分钟
        if ($this->pCookie('com') && isset($Query->com)) {
            $this->sCookie('com', 5400);
        }

        if (isset($Query->com)) {
            // spread++
            $spreadUpdateSql = "UPDATE " . COMPANY_SPREAD . " SET `readi` = `readi` + 1 WHERE `product_id` = $Query->id AND `com_id` = '$Query->com';";
            $this->Db->query($spreadUpdateSql);
        }

        // $openid = $this->getOpenId();

        $Query->id = intval($Query->id);
        $this->cacheId = $Query->id;

        if (!$this->isCached($Query->id)) {
            $this->loadModel('Product');
            // productinfo
            $productInfo = $this->Db->getOneRow(sprintf("SELECT * FROM `vproductinfo` WHERE product_id = %s;", $Query->id));
            $images = $this->Db->query("SELECT * FROM `product_images` WHERE `product_id` = $Query->id;");
            $productInfo['images'] = $images;
            $productInfo2 = $this->Db->getOneRow(sprintf("SELECT * FROM `products_info` WHERE product_id = %s;", $Query->id));
            // 随机product推荐
            $sList = $this->Product->randomGetProducts(6);
            $this->Smarty->assign('slist',$sList);
            $this->Smarty->assign('shareimg', $this->root . 'static/product_hpic/' . $productInfo['catimg']);
            $this->Smarty->assign('showSbar', count($images) > 1);
            $this->Smarty->assign('images', $images);
            $this->Smarty->assign('productInfo', $productInfo);
            $this->Smarty->assign('productInfo2', $productInfo2);
            $this->Smarty->assign('productid', $Query->id);
            // $this->Smarty->assign('comid', $openid);
            $this->Smarty->assign('title', $productInfo['product_name']);
        }

        // readi
        $this->Db->query("UPDATE `products_info` SET `product_readi` = `product_readi` + 1 WHERE `product_id` = $Query->id;");

        $this->show();
    }

    /**
     * 查看产品分类介绍
     * @param type $Query
     */
    public final function view_category($Query) {
        !isset($Query->cat) && $Query->cat = 0;

        $this->cacheId = $Query->cat;

        // 缓存
        if (!$this->isCached()) {
            $this->loadModel('Product');
            $topCats = $this->Product->getCatList(0);
            $catInfo = $this->Product->getCatInfo($Query->cat);
            $subCatInfo = $this->Product->getCatList($catInfo['cat_id']);
            $this->Smarty->assign('topcat', $topCats);
            $this->Smarty->assign('subcat', $subCatInfo);
            $this->Smarty->assign('title', '产品搜索');
            $this->Smarty->assign('cat', $Query->cat);
            $this->Smarty->assign('cat_descs', $catInfo['cat_descs']);
        }

        $this->show();
    }

    /**
     * ajax获取分类列表视图
     * @param type $Query
     */
    public final function ajaxCatList($Query) {
        if (isset($Query->id)) {
            $this->loadModel('Product');
            $subCatInfo = $this->Product->getCatList($Query->id);
            foreach ($subCatInfo as &$s) {
                $childrens = $this->Product->getCatList($s['cat_id']);
                if (count($childrens) > 0) {
                    $s['child'] = $childrens;
                } else {
                    $s['child'] = false;
                }
            }
            $this->cacheId = $Query->id;
            $this->Smarty->assign('subcat', $subCatInfo);
            $this->show();
        }
    }

    /**
     * 商品列表
     * @param type $Query
     */
    public function view_list($Query) {
        $this->getOpenId();

        !isset($Query->page) && $Query->page = 0;
        !isset($Query->searchkey) && $Query->searchkey = '';
        !isset($Query->cat) && $Query->cat = 1;
        !isset($Query->orderby) && $Query->orderby = "";
        $Query->searchkey = urldecode($Query->searchkey);

        $this->cacheId = md5(serialize($Query));

        // 推荐com，90分钟
        if (!isset($this->pGet['com']) && isset($Query->com)) {
            setcookie("com", $Query->com, time() + 5400);
        }

        if (!$this->isCached()) {
            // params
            if ($Query->searchkey != '') {
                $catInfo = array(
                    'cat_id' => $Query->cat,
                    'cat_name' => $Query->searchkey . '的搜索结果'
                );
            } else {
                $this->loadModel('Product');
                $catInfo = $this->Product->getCatInfo($Query->cat);
            }

            $this->Smarty->assign('query', $Query);
            $this->Smarty->assign('searchkey', $Query->searchkey);
            $this->Smarty->assign('cat', $Query->cat);
            $this->Smarty->assign('catInfo', $catInfo);
            $this->Smarty->assign('orderby', $Query->orderby);
            $this->Smarty->assign('title', $catInfo['cat_name']);
        }

        $this->show();
    }

    /**
     * Ajax返回商品列表 分页
     * @todo cat
     * @param type $Query
     */
    public function ajaxProductList($Query) {
        // page
        !isset($Query->page) && $Query->page = 0;
        // order by
        if (!isset($Query->orderby) || $Query->orderby == "") {
            $Query->orderby = '`sort` DESC';
        } else {
            $Query->orderby = trim(urldecode($Query->orderby));
        }
        // product category
        !isset($Query->cat) && $Query->cat = 1;

        $this->cacheId = md5(serialize($Query));

        if (!$this->isCached()) {
            // Query limit statment
            $_SQL_limit = $Query->page * self::LIST_LIMIT . "," . self::LIST_LIMIT;
            // search key
            if (isset($Query->searchKey) && $Query->searchKey != '') {
                $Query->searchKey = urldecode($Query->searchKey);
                $_SQL = sprintf("SELECT * FROM `vproductinfo` WHERE `product_name` LIKE '%%$Query->searchKey%%' AND `delete` = 0 ORDER BY %s LIMIT %s;", $Query->orderby, $_SQL_limit);
            } else {
                $_SQL = sprintf("SELECT * FROM `vproductinfo` WHERE `product_cat` = $Query->cat AND `delete` = 0 ORDER BY %s LIMIT %s;", $Query->orderby, $_SQL_limit);
            }
            $productList = $this->Db->query($_SQL);
            if (count($productList) == 0) {
                $this->Smarty->assign('product_list', false);
            } else {
                $this->Smarty->assign('product_list', $productList);
            }
            $this->Smarty->assign('stype', $Query->stype);
        }

        $this->show();
    }

    /**
     * Cart data
     * @return HTML STRING
     */
    public function cartData() {
        $data = json_decode($_POST['data'], true);
        $_tmp = array();
        foreach ($data as $key => $product) {
            array_push($_tmp, $key);
        }
        $_SQL = sprintf("SELECT * FROM `vproductinfo` WHERE `product_id` IN (%s);", implode(',', $_tmp));
        $this->Smarty->assign('product_list', $this->Db->query($_SQL));
        $this->Smarty->assign('product_data', $data);
        $this->show();
    }

    /**
     * 上传封面图片
     * ImageUpload
     */
    public function ImageUpload($Query) {
        global $config;
        !isset($Query->name) && $Query->name = '';
        if (!empty($GLOBALS["HTTP_RAW_POST_DATA"])) {
            $targetPath = dirname(__FILE__) . "/../static/product_hpic2/";
            $targetFileName = sha1(uniqid() . rand(1, 1500)) . '^' . $Query->name;
            $targetFile = $targetPath . $targetFileName;
            $state = file_put_contents($targetFile, $GLOBALS["HTTP_RAW_POST_DATA"]) > 0 ? 1 : 0;
        } else {
            $state = 0;
        }
        $this->echoJson(array(
            "status" => $state,
            "imagepath" => urlencode("http://" . $_SERVER['HTTP_HOST'] . $config->shoproot . 'static/product_hpic2/' . $targetFileName),
            "imagename" => $targetFileName
        ));
    }

    /**
     * 
     * @param type $Query
     */
    public function ajaxGetCategroys() {
        $this->loadModel('Product');
        $cats = $this->Product->getAllCats();
        echo $this->unIescape($this->toJson($cats));
    }

    /**
     * 
     * @param type $catname
     * @param type $pid
     */
    public function ajaxAddCategroy() {
        $catname = trim($this->post('catname'));
        $pid = intval($this->post('pid'));
        echo $this->Db->query("INSERT INTO `product_category` (cat_name,cat_parent) VALUES ('$catname',$pid);");
    }

    /**
     * 
     * @param type $catname
     * @param type $pid
     */
    public function ajaxDelCategroy() {
        $id = $this->post('id');
        echo $this->Db->query("DELETE FROM `product_category` WHERE cat_id = $id;");
    }

    /**
     * alter
     */
    public function ajaxAlterCategroy() {
        $catid = intval($this->post('catid'));
        $catname = trim($this->post('catname'));
        $catimage = $this->post('catimage');
        $catdesc = $this->post('catdesc');
        #echo "UPDATE `product_category` SET cat_name = '$catname',cat_image = '$catimage',cat_descs = '$catdesc' WHERE cat_id = $catid;";
        echo $this->Db->query("UPDATE `product_category` SET cat_name = '$catname',cat_image = '$catimage',cat_descs = '$catdesc' WHERE cat_id = $catid;");
    }

}
